package com.mac.web.controller.bill;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.mac.common.utils.DateUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.mac.common.annotation.Log;
import com.mac.common.core.controller.BaseController;
import com.mac.common.core.domain.AjaxResult;
import com.mac.common.enums.BusinessType;
import com.mac.bill.domain.BillTel;
import com.mac.bill.service.IBillTelService;
import com.mac.common.utils.poi.ExcelUtil;
import com.mac.common.core.page.TableDataInfo;

/**
 * 话单Controller
 *
 * @author mac
 * @date 2023-04-08
 */
@RestController
@RequestMapping("/bill/tel")
public class BillTelController extends BaseController {
    @Autowired
    private IBillTelService billTelService;
    private static final String PATTERN = "yyyy-MM-dd HH:mm";

    private static final long MIN_TIME = 10 * 60 * 1000;

    /**
     * 查询话单列表
     */
    @PreAuthorize("@ss.hasPermi('bill:tel:list')")
    @GetMapping("/list")
    public TableDataInfo list(BillTel billTel) {
        startPage();
        List<BillTel> list = billTelService.selectBillTelList(billTel);
        return getDataTable(list);
    }

    @GetMapping("/list1")
    public Set<String> list1() {
        return billTelService.selectBillTelListLike();

    }

    static class Demo {
        private List<BillTel> billTels;

        public List<BillTel> getBillTels() {
            return billTels;
        }

        public void setBillTels(List<BillTel> billTels) {
            this.billTels = billTels;
        }
    }

    @GetMapping("/typeList")
    public AjaxResult typeList(Object object) {
        BillTel billTel = new BillTel();
//        if ("null".equals(sendTel)) sendTel = null;
//        billTel.setSendTel(sendTel);
        List<BillTel> billTels = billTelService.selectBillTelList(billTel);
        List<String> startAtList = billTels.stream().sorted(Comparator.comparing(BillTel::getStartAt))
                .map(BillTel::getStartAt).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(startAtList)) {
            int times = 0;
            String tempTime = startAtList.get(0);
            long tempDate = DateUtils.dateTime(PATTERN, tempTime + MIN_TIME).getTime();
            List<List<String>> data = new ArrayList<>();
            Map<String, Integer> map = new LinkedHashMap<>();
            for (String startTime : startAtList) {
                times++;
                long currentDate = DateUtils.dateTime(PATTERN, startTime).getTime();
                String format = DateFormatUtils.format(tempDate - MIN_TIME, PATTERN);
                if (currentDate > tempDate) {
                    tempDate = currentDate + MIN_TIME;
                    map.put(format, times);
                    times = 0;
                    continue;
                }
                map.put(format, times);
            }

            map.entrySet()
                    .stream().sorted(Map.Entry.comparingByValue())
                    .forEachOrdered(t -> map.put(t.getKey(), t.getValue()));

            List<String> item;
            for (Map.Entry<String, Integer> entry : map.entrySet()) {
                item = new ArrayList<>();
                item.add(entry.getKey());
                item.add(String.valueOf(entry.getValue()));
                data.add(item);
            }

            return AjaxResult.success(data);
        }


        return AjaxResult.success();
    }

    /**
     * 导出话单列表
     */
    @PreAuthorize("@ss.hasPermi('bill:tel:export')")
    @Log(title = "话单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestParam("ids") Long[] ids) {
        List<BillTel> list = billTelService.selectBillTelByIds(ids);
        ExcelUtil<BillTel> util = new ExcelUtil<BillTel>(BillTel.class);
        util.exportExcel(response, list, "话单数据");
    }

    /**
     * 获取话单详细信息
     */
    @PreAuthorize("@ss.hasPermi('bill:tel:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(billTelService.selectBillTelById(id));
    }

    /**
     * 新增话单
     */
    @PreAuthorize("@ss.hasPermi('bill:tel:add')")
    @Log(title = "话单", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BillTel billTel) {
        return toAjax(billTelService.insertBillTel(billTel));
    }

    /**
     * 修改话单
     */
    @PreAuthorize("@ss.hasPermi('bill:tel:edit')")
    @Log(title = "话单", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BillTel billTel) {
        return toAjax(billTelService.updateBillTel(billTel));
    }

    /**
     * 删除话单
     */
    @PreAuthorize("@ss.hasPermi('bill:tel:remove')")
    @Log(title = "话单", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(billTelService.deleteBillTelByIds(ids));
    }
}
